package br.com.feltex.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.feltex.entidade.Aluno;

public class AlunoDAO {

	private Session session;

	public void incluir(Aluno aluno) {
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			session.save(aluno);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public void alterar(Aluno aluno) {
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			session.merge(aluno);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public void excluir(Aluno aluno) {
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			session.delete(aluno);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public Aluno consultar(long codigo) {
		Aluno retorno = new Aluno();
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			retorno = (Aluno) session.get(Aluno.class, codigo);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return retorno;
	}

	@SuppressWarnings("unchecked")
	public List<Aluno> listar() {
		List<Aluno> lista = new ArrayList<Aluno>();
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			lista = (List<Aluno>) session.createCriteria(Aluno.class).list();
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return lista;
	}

	@SuppressWarnings("unchecked")
	public List<Aluno> listar(Aluno aluno) {
		Criteria c = session.createCriteria(Aluno.class);
		if (aluno.getNome().length() > 0) {
			c.add(Restrictions.like("nome", aluno.getNome() + "%"));
		}
		c.addOrder(Order.asc("nome"));
		return (List<Aluno>) c.list();
	}

}
